package es.udc.emarketapp.http.controller.actions.products;

import es.udc.emarketapp.emarket.model.country.vo.CountryVO;
import es.udc.emarketapp.emarket.model.countryFacade.CountryFacade;
import es.udc.emarketapp.emarket.model.product.vo.ProductVO;
import es.udc.emarketapp.emarket.model.productFacade.ProductFacade;
import es.udc.emarketapp.http.view.actionForms.BuyProductForm;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class FindProductAction extends DefaultAction {

    public ActionForward doExecute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException, InternalErrorException {

        /* Get data. */
        //long idProd = new Long(request.getParameter("idProd"));

        long idProd = Integer.parseInt(request.getParameter("idProd"));

        if (request.getParameter("idProd") == null) {
            idProd = ((BuyProductForm) form).getIdProd();
        }

        /* Do action. */
        return doFindProduct(mapping, idProd, request);

    }

    private ActionForward doFindProduct(ActionMapping mapping, Long idProd,
            HttpServletRequest request) throws InternalErrorException {

        ActionMessages errors = new ActionMessages();

        ProductFacade productsFacade = new ProductFacade();
        ProductVO productVO = null;

        try {

            productVO = productsFacade.findProductById(idProd);

        } catch (InstanceNotFoundException e) {
            errors.add("ProductIdentifier",
                    new ActionMessage("ErrorMessages.product.notFound"));
            saveErrors(request, errors);
        }

        CountryFacade countryFacade = new CountryFacade();
        CountryVO pais = null;

        Locale locale = getLocale(request);

        try {
            pais = countryFacade.findById(productVO.getPaisOrigen(), locale.getLanguage());
            productVO.setPaisOrigen(pais.getNomPais());

        } catch (InstanceNotFoundException e) {
            errors.add("countryIdentifier",
                    new ActionMessage("ErrorMessages.country.notFound"));
            saveErrors(request, errors);
        }

        request.setAttribute("product", productVO);


        /* Return ActionForward. */
        return mapping.findForward("success");
    }
}
